<template>
<div style="padding: 10px;background-color: #f5f5f5;height: calc(100vh - 60px);overflow-y: auto">
  <div style="background-color: white;padding: 5px;border-radius: 10px">
    <div style="margin-bottom: 10px">
      <el-button size="small" type="primary" @click="addGoods">添加商品</el-button>
    </div>
  <el-table :data="tableData" border style="width: 100%">
    <el-table-column label="商品名称" width="180">
      <template slot-scope="scope">
        <div style="display: flex;align-items: center;height: 50px">
          <div>  <img :src="scope.row.itemImages.includes(';')?scope.row.itemImages.split(';')[0]:scope.row.itemImages" style="width: 50px;height: 50px;object-fit: cover;border-radius: 10px"></div>
          <div style="margin-left: 5px">
            <el-tooltip class="item" effect="dark" :content="scope.row.itemTitle" placement="right">
              <div style="max-width: 130px; overflow: hidden; text-overflow: ellipsis;white-space: nowrap;">{{scope.row.itemTitle}}</div>
            </el-tooltip>
          </div>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="category" label="分类" width="180"></el-table-column>
    <el-table-column prop="itemTitle" label="商品标题"></el-table-column>
    <el-table-column prop="itemDescription" label="商品描述"></el-table-column>
    <el-table-column  label="规格">
      <template slot-scope="scope">
        <el-button type="text" @click="showSpec(scope.row)">查看规格</el-button>
      </template>
    </el-table-column>
    <el-table-column  label="商品详情">
      <template slot-scope="scope">
        <div style="display: flex;align-items: center;height: 50px">
          <div v-if="scope.row.detail">
            <el-image style="width: 50px;height: 50px;border-radius: 10px" fit="cover" :src="scope.row.detail.includes(';')?scope.row.detail.split(';')[0]:scope.row.detail" :preview-src-list="scope.row.preview"></el-image></div>
        </div>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" width="200px">
      <template slot-scope="scope">
        <el-button type="primary" size="mini" icon="el-icon-circle-plus"  @click="editGood(scope.row)">编辑</el-button>
<!--        <el-button type="warning" slot="reference"   size="mini" style="margin-left: 0px" icon="el-icon-delete-solid" @click="delete1(scope.row)">删除</el-button>-->
      </template>
    </el-table-column>
  </el-table>
    <!--        分页-->
    <div class="pagination-container" style="text-align: center">
      <el-pagination
        class="pagiantion"
        v-show="total>0"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageParams.pageNum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="pageParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
  </div>
<!--  规格弹窗-->
  <el-dialog title="规格" :visible.sync="specShow" min-width="80%" >
    <el-button size="mini" style="margin-bottom: 10px" icon="el-icon-circle-plus" circle @click="addSpec"></el-button>
    <el-button size="mini" style="margin-bottom: 10px" icon="el-icon-s-marketing" circle @click="calcSpec"></el-button>
    <div style="display: flex">
      <div style="min-width: 56px">规格类：</div>
      <div><div v-for="(items,index) in specs" :key="index">
        <div style="display: flex;">
          <div style="width: 100px"><el-input size="small" v-model="items.name"></el-input></div>
<!--          各项规格的值-->
          <div style="margin-left: 5px;margin-bottom: 5px;">
            <el-tag style="margin-bottom: 5px"
              :key="tag"
              v-for="(tag,i) in items.value"
              closable
              :disable-transitions="false"
              @close="handleClose(tag,index,i)">
              <el-tooltip class="item" effect="dark" :content="tag" placement="top">
                <span> {{tag}}</span>
              </el-tooltip>

            </el-tag>
            <el-input
              style="min-width: 150px"
              class="input-new-tag"
              v-if="specs[index].inputVisible==true"
              v-model="items.inputTag"
              size="small"
              @keyup.enter.native="handleInputConfirm(index)"
              @blur="handleInputConfirm(index)">
            </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput(index)">+ 规格新值</el-button>
            <el-button class="button-new-tag" size="small" @click="deleteSpec(index)">- 删除规格</el-button>
          </div>
          </div>
        </div>
      </div>
    </div>
<!--    组装规格-->
    <el-divider content-position="center" v-if="specs.length>0">组装规格</el-divider>
    <div v-for="items in specAll" :key="items" style="margin-bottom: 10px" v-if="specs.length>0">
      <div style="display:flex;align-items: center">
        <div style="font-weight: bold">{{items.specification}}</div>
        <div style="font-weight: bold;margin-left: 10px">库存： <el-input-number size="mini" v-model="items.stock" :min="1" :max="100000" label="商品库存"></el-input-number></div>
        <div style="font-weight: bold;margin-left: 10px">价格：<el-input-number size="mini" v-model="items.price" :precision="2" :step="0.1" :max="1000000"></el-input-number></div>
      </div>
    </div>
    <div style="text-align: center" v-if="specs.length>0"><el-button type="primary" @click="saveSpecs(items)">保存</el-button><el-button @click="specShow=false">取消</el-button></div>
  </el-dialog>
<!--  添加或修改商品-->
  <el-dialog :title="goodTitle" :visible.sync="goodsShow" width="40%">
    <el-form :model="good"  ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="分类" prop="category">
        <el-cascader v-model="good.cateIds" :options="catOption" @change="handleChange" :clearable="false"></el-cascader>
      </el-form-item>
      <el-form-item label="商品标题" prop="itemTitle">
        <el-input v-model="good.itemTitle"></el-input>
      </el-form-item>
      <el-form-item label="商品描述" prop="itemDescription">
        <el-input v-model="good.itemDescription"></el-input>
      </el-form-item>
      <el-form-item label="商品图片" >
        <template slot-scope="props">
          <el-upload
            list-type="picture-card"
            :action="uploadAction"
            :on-remove="handleRemove"
            :headers="{'token':userToken}"
            :on-success="handleAvatarSuccess"
            :file-list="fileList">
             <i class="el-icon-plus"></i>
          </el-upload>
        </template>
      </el-form-item>
      <el-form-item label="商品详情" >
        <template slot-scope="props">
          <el-upload
            list-type="picture-card"
            :action="uploadAction"
            :on-remove="handleRemove2"
            :headers="{'token':userToken}"
            :on-success="handleAvatarSuccess2"
            :file-list="fileList2">
            <i class="el-icon-plus"></i>
          </el-upload>
        </template>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即提交</el-button>
        <el-button @click="goodsShow=false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</div>
</template>
<script>
import request from "../utils/request";
import {dev as globalConfig} from "../../config";

export default {
  name: "goods",
  data(){
    return{
      total:0,
      fileList2:[],
      fileList:[],
      userToken:localStorage.getItem("token"),
      dialogImageUrl: '',
      dialogVisible: false,
      catOption:[],//分类
      goodTitle:'',
      goodsShow:false,
      good:{},
      spec:{},
      specAll:[],
      inputValue: '',
      specs:[],//规格类
      specShow:false,
      tableData: [],
      pageParams:{
        pageNum:1,
        pageSize:10
      },
      isCalc:false
    }
  },
  computed: {
    uploadAction() {
      return 'http://' + globalConfig.host + ':8090/upload/';
    }
  },
  created() {
    this.getData()
  },
  methods:{
    //提交修改或新增
    onSubmit(){
      request.post('/productDetails/addUpdateGood',this.good).then(resp=>{
        if (resp.code===0){
          this.goodsShow=false
          this.message(resp.errorMessage,'success')
        }
      })
    },
    //编辑商品
    editGood(i){
      this.fileList=[]
      this.fileList2=[]
      if (i.itemImages.includes(';')){
        for (let j = 0; j < i.itemImages.split(';').length; j++) {
          let url={name:'',url:i.itemImages.split(';')[j]}
          this.fileList.push(url)
        }
      }else {
        let url={name:'',url:i.itemImages}
        this.fileList.push(url)
      }
      if (i.detail&&i.detail.includes(';')){
        for (let j = 0; j < i.detail.split(';').length; j++) {
          let url={name:'',url:i.detail.split(';')[j]}
          this.fileList.push(url)
        }
      }else {
        let url={name:'',url:i.detail}
        this.fileList2.push(url)
      }
      //查询分类
      request.get('/productCategories/getAll').then(resp=>{
        if (resp.code===0){
          this.catOption=resp.data
          this.goodTitle='编辑商品'
          this.good=i
          this.goodsShow=true
        }
      })

    },
    handleChange(value){
      this.good.itemId=value[1]
    },
    //添加商品
    addGoods(){
      this.fileList=[]
      this.fileList2=[]
      this.good={}
      this.goodTitle='新增商品'
      //查询分类
      request.get('/productCategories/getAll').then(resp=>{
        if (resp.code===0){
          this.catOption=resp.data
        }
      })
      this.goodsShow=true
    },
    addSpec(){
      let spec={inputVisible:false,value:[],}
      this.specs.push(spec)
    },
    handleClose(tag,index,i) {
      this.specs[index].value.splice(i, 1);
    },
    showInput(index) {
      this.specs[index].inputVisible = true;

    },
    handleInputConfirm(i) {
      if (this.specs[i].inputTag) {
        this.specs[i].value.push(this.specs[i].inputTag)
      }
      this.specs[i].inputVisible = false;
      this.specs[i].inputTag = '';

    },
    //保存规格
    saveSpecs(){
      console.log(this.specAll)
      request.post('/specfication/updateSpec',{isCalc:this.isCalc,id:this.spec.id,specs:this.specAll}).then(resp=>{
        if (resp.code===0){
          this.specShow=false
          this.message(resp.errorMessage,'success')
        }
      })
    },
    //组装规格
    calcSpec(){
      this.isCalc=true
      const results = [];
      this.combineSpecs(this.specs, results, 0, {});
      this.specAll=results.map(result => ({specification: Object.entries(result).map(([k, v]) => `${k}:${v}`).join(';')}))
      console.log(results.map(result => ({specification: Object.entries(result).map(([k, v]) => `${k}:${v}`).join(';')})));
    },
    //组装函数
    combineSpecs(specs, results, depth, currentResult) {
      if (depth === specs.length) {
        results.push(currentResult);
        return;
      }

      const spec = specs[depth];
      for (let i = 0; i < spec.value.length; i++) {
        const value = spec.value[i];
        currentResult[spec.name] = value;
        this.combineSpecs(specs, results, depth + 1, Object.assign({}, currentResult));
        delete currentResult[spec.name];
      }
    },
    //删除规格
    deleteSpec(i){
      this.specs.splice(i,1)
    },
    // 查看规格
    showSpec(row){
      this.isCalc=false
      this.spec=row
      this.specShow=true
      request.post('/productDetails/getSpec',{id:row.id}).then(resp=>{
        this.specs=resp.data
        if (!resp.data){
          this.specs=[]
        }
        this.specAll=resp.msg
      })
    },
    getData(){
      request.post('/productDetails/getDetails',this.pageParams).then(resp=>{
        if (resp.code===200){
          for (let i = 0; i < resp.list.length; i++) {
            resp.list[i].preview=[]
            if (resp.list[i].detail&&resp.list[i].detail.includes(';')){
              for (let j = 0; j < resp.list[i].detail.split(';').length; j++) {
                resp.list[i].preview.push(resp.list[i].detail.split(';')[j])
              }
            }else {
              resp.list[i].preview.push(resp.list[i].detail)
            }
          }
          this.tableData=resp.list
          this.total=resp.total
        }
      })
    },
    handleAvatarSuccess(res, file) {
      if (this.good.itemImages){
        this.good.itemImages+=';'+res.data
      }else {
        this.good.itemImages=res.data
      }
      alert(this.good.itemImages)
    },
    handleRemove(file, fileList){
      this.good.itemImages=''
      if (fileList.length>1){
        this.good.itemImages=fileList[0].url
        for (let i = 1; i < fileList.length; i++) {
          this.good.itemImages+=';'+fileList[i].url
        }
      }else {
        if (fileList.length==1){
          this.good.itemImages=fileList[0].url
        }
      }
    },
    handleAvatarSuccess2(res, file) {
      if (this.good.detail){
        this.good.detail+=';'+res.data
      }else {
        this.good.detail=res.data
      }
    },
    handleRemove2(file, fileList){
      this.good.detail=''
      if (fileList.length>1){
        this.good.detail=fileList[0].url
        for (let i = 1; i < fileList.length; i++) {
          this.good.detail+=';'+fileList[i].url
        }
      }else {
        if (fileList.length==1){
          this.good.detail=fileList[0].url
        }
      }
    },
    //分页
    handleSizeChange(val){
      this.pageParams.pageSize = val;
      this.pageParams.pageNum = 1;
      this.getData()
    },
    handleCurrentChange(val){
      this.pageParams.pageNum = val;
      this.getData()
    },
  }
}
</script>

<style scoped>
>>> .el-dialog{
  width: 70%;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
>>> .el-input--small{
  min-width: 100px;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
>>> .el-dialog__body{
  padding: 10px 20px;
}
</style>
